<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryinfo.query"
            clearable
            @clear="getUserList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="userdialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 角色分配按钮 -->
            <el-tooltip
              effect="dark"
              content="角色分配"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="openRoleDia(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- Pagination 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户弹出层 -->
    <el-dialog
      title="添加用户"
      :visible.sync="userdialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 表单 -->
      <el-form
        :model="newUser"
        :rules="addrules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="newUser.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            v-model="newUser.password"
            :type="isPasswordShow ? '' : 'password'"
          >
            <i
              slot="suffix"
              :class="
                !isPasswordShow
                  ? 'el-input__icon el-icon-view el-mima-hidden'
                  : 'el-input__icon el-icon-view el-mima-show'
              "
              @click="isPasswordShow = !isPasswordShow"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="newUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="userdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户弹出层 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 表单 -->
      <el-form
        :model="editForm"
        :rules="addrules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名称">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹出层 -->
    <el-dialog
      title="角色分配"
      :visible.sync="roleDialogVisible"
      width="50%"
      @close="roleDialogClose"
    >
      <!-- 表单 -->
      <el-form ref="roleFormRef" label-width="70px">
        <p>当前的用户： {{ userRoleInfo.username }}</p>
        <p>当前的角色： {{ userRoleInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleSubmit(userRoleInfo)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮件的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入一个合法的邮箱地址!'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证邮件的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入一个合法的手机号码!'))
    }
    return {
      // 获取用户列表的参数对象
      queryinfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 用户列表
      userlist: [],
      // 总数据条数
      total: 0,
      // 新建表用户信息
      newUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 当前用户信息
      userRoleInfo: {},
      // 所有角色
      roleList: [],
      // 分配新角色时，选中的新角色id
      selectedRoleId: '',
      // 密码是否可见
      isPasswordShow: false,
      // Dialog显隐
      userdialogVisible: false,
      // 校验规则
      addrules: {
        username: [
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // { validator: checkEmail, trigger: 'blur' }
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框显隐
      editDialogVisible: false,
      // 控制分配角色对话框显隐
      roleDialogVisible: false,
      // 查询到的用户信息保存
      editForm: {}
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryinfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败！')
      this.userlist = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    // 监听 pagesize 改变事件
    handleSizeChange (val) {
      this.queryinfo.pagesize = val
      this.getUserList()
    },
    // 监听 页码值 改变事件
    handleCurrentChange (val) {
      this.queryinfo.pagenum = val
      this.getUserList()
    },
    // 状态变化
    async userStateChanged (val) {
      const { data: res } = await this.$http.put(`users/${val.id}/state/${val.mg_state}`)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error('用户状态更新失败')
      }
      this.$message.success('用户状态更新成功')
    },
    // 添加用户
    async addUser () {
      // 表单预验证
      this.$refs.addFormRef.validate(async valid => {
        // 预验证失败，直接返回
        if (!valid) return
        // 预验证成功，赋值解构异步请求中的data，并赋值给res
        const { data: res } = await this.$http.post('users', this.newUser)
        // 检测状态码，201为请求成功
        if (res.meta.status !== 201) this.$message.error('用户添加失败')
        // 打印成功提示
        this.$message.success(`${res.meta.msg}`)
        // 关闭添加面板
        this.userdialogVisible = false
        // 刷新列表
        this.getUserList()
      })
    },
    // 关闭添加用户Dialog窗口,重置表单
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 关闭分配角色Dialog窗口,重置表单
    roleDialogClose () {
      this.$refs.roleFormRef.resetFields()
    },
    // 关闭修改用户Dialog窗口,重置表单
    editDialogClose () {
      // 重置表单
      this.$refs.editFormRef.resetFields()
      // 修复动画造成的数据改变重影
      this.newUser = {}
    },
    // 展示修改用户Dialog窗口
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('查询用户信息失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改用户信息
    async editUserInfo () {
      // 表单预验证
      this.$refs.editFormRef.validate(async valid => {
        // 预验证失败，直接返回
        if (!valid) return
        // 预验证成功，赋值解构异步请求中的data，并赋值给res
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`, this.editForm)
        // 检测状态码，200为请求成功
        if (res.meta.status !== 200) return this.$message.error('用户信息编辑失败')
        // 打印成功提示
        this.$message.success('修改成功')
        // 刷新列表
        this.getUserList()
        // 关闭添加面板
        this.editDialogVisible = false
      })
    },
    // 删除用户
    deleteUser (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败！请稍后再试！')
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      // console.log(id)
    },
    // 打开分配角色Dialog窗口
    async openRoleDia (info) {
      this.userRoleInfo = info
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = res.data
      this.roleDialogVisible = true
    },
    // 确定角色分配
    async roleSubmit (info) {
      // console.log(info)
      const { data: res } = await this.$http.put(`users/${info.id}/role`, { rid: this.selectedRoleId })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('角色分配成功！')
      this.getUserList()
      this.roleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-mima-show {
  cursor: pointer;
  font-size: 22px;
  color: #409eff;
}
.el-mima-hidden {
  cursor: pointer;
  font-size: 22px;
  color: #606266;
}
</style>
